package com.xh.xyzp.controller;

import cn.hutool.core.util.RandomUtil;
import com.xh.xyzp.common.domain.vo.resp.ApiResult;
import com.xh.xyzp.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

/**
 * @Author: xianghao
 * @Description:
 * @Date: 2025-04-18  14:03
 */
@Api(tags = "邮件接口")
@RestController
@RequestMapping("/email")
public class EmailController {

    @Autowired
    private JavaMailSender mailSender;

    @ApiOperation("发送注册邮件")
    @PostMapping("/send/{email}")
    public ApiResult<Void> send(@PathVariable("email") String email) throws MessagingException {
        String code = RandomUtil.randomNumbers(4);
        RedisUtil.set("register_email_code:" + email, code, 5, TimeUnit.MINUTES);
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("2770063826@qq.com");
        helper.setTo(email);
        helper.setSubject("注册邮件");
        helper.setText(String.format(
                "<html>" +
                        "<body style='font-family: Arial, sans-serif; line-height: 1.5;'>" +
                        "<div style='max-width: 600px; margin: auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 5px;'>" +
                        "<h2 style='color: #333;'>尊敬的用户，</h2>" +
                        "<p>您好！感谢您使用我们的服务。</p>" +
                        "<p>您的验证码是：<span style='font-size: 18px; font-weight:600'>%s</span>，有效期为 <strong>5分钟</strong>。</p>" +
                        "<p>请您在有效期内使用此验证码进行操作。</p>" +
                        "<p>如您并未发起此请求，您可以安全地忽略此邮件。</p>" +
                        "<p>为了保障您的账户安全，请勿将此验证码透露给他人。</p>" +
                        "<p>感谢您的配合与支持！</p>" +
                        "<p>祝您生活愉快！</p>" +
                        "<footer style='margin-top: 20px; font-size: 12px; color: #777;'>本邮件由系统自动生成，请勿回复。</footer>" +
                        "</div>" +
                        "</body>" +
                        "</html>",
                code), true);
        mailSender.send(message);

        return ApiResult.success();
    }

}
